<template>
	<div>
		<!-- <el-breadcrumb separator="/" style="margin-bottom: 20px; margin-top: 20px">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>优惠券管理</el-breadcrumb-item>
			<el-breadcrumb-item>券活动管理</el-breadcrumb-item>
			<el-breadcrumb-item>兑换码管理</el-breadcrumb-item>
		</el-breadcrumb> -->
		<div style="margin-bottom: 20px">
      <el-button type="primary" @click="templateAdd()"><i class="el-icon-plus"></i>满返</el-button>
    </div>
		<el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="分公司" style="margin-right:30px">
        <el-select v-if="!brachDisabled" v-model="formInline.branchId" :disabled="brachDisabled"
        @change="getDeptList" @visible-change="visibleChange" style="width:195px" placeholder="分公司">
          <el-option v-for="(item, index) in this.branchList" :value="item.branch_Id" :label="item.branch_Name" :key="index"></el-option>
        </el-select>
        <el-input v-if="brachDisabled" v-model="showBranch" :disabled="brachDisabled" style="width:195px"></el-input>
      </el-form-item>
      <el-form-item label="所属部门" style="margin-right:30px">
        <el-select v-if="!brachDisabled" v-model="formInline.deptId" :disabled="brachDisabled" placeholder="所属部门" style="width:195px">
          <el-option v-for="(item, index) in this.deptList" :value="item.org_id" :label="item.org_name" :key="index"></el-option>
        </el-select>
        <el-input v-if="brachDisabled" v-model="this.showDept" disabled style="width:195px"></el-input>
      </el-form-item>
      <el-form-item label="批次状态" style="margin-right:30px">
        <el-select v-model="formInline.state" @change="pageChange" filterable clearable style="width:195px">
          <el-option label="草稿" value="1"></el-option>
          <el-option label="待审核" value="2"></el-option>
          <el-option label="审核中" value="3"></el-option>
          <el-option label="审核不通过" value="4"></el-option>
          <el-option label="未开始" value="5"></el-option>
          <el-option label="进行中" value="6"></el-option>
          <el-option label="已结束" value="7"></el-option>
          <el-option label="已作废" value="99"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="活动起止时间">
				<el-date-picker
          :editable="false"
          v-model="formInline.startStopTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          style="width:195px"
          @change="daterangeFormat"
          placeholder="批次有效期">
				</el-date-picker>
			</el-form-item>
			<el-form-item label="批次ID" style="margin-right:30px">
				<el-input v-model="formInline.batchId" style="width:195px" placeholder="请输入批次ID"></el-input>
			</el-form-item>
      <el-form-item label="活动ID" style="margin-right:30px">
        <el-input v-model="formInline.phpId" style="width:195px" placeholder="请输入活动Id"></el-input>
      </el-form-item>
			<el-form-item label="批次名称" style="margin-right:30px">
				<el-input v-model="formInline.batchName" style="width:195px" placeholder="请输入批次名称"></el-input>
			</el-form-item>
			<!-- <el-form-item label="兑换码" label-width="68px" style="margin-right:30px">
				<el-input v-model="formInline.code" style="width:195px" placeholder="请输入兑换码"></el-input>
			</el-form-item> -->
			<el-form-item>
        <el-button type="primary"  @click="searchList">查询</el-button>
        <el-button type="primary" @click="checkColumn = true">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="isLoading" :data="tableData" style="width: 100%" border>
      <el-table-column prop="branchName" label="分公司" align="center" min-width="130"></el-table-column>
      <el-table-column prop="departName" label="所属部门" align="center" width="100"></el-table-column>
      <el-table-column prop="id" label="批次ID" align="center" width="80"></el-table-column>
      <el-table-column prop="phpId" label="活动ID" align="center" width="80"></el-table-column>
      <el-table-column prop="batchName" label="批次名称" align="center" show-overflow-tooltip  min-width="140"></el-table-column>
      <el-table-column label="达成类型" align="center" width="90">
        <template scope="scope">
          <span v-if="scope.row.fullRule === 1">阶梯</span>
          <span v-if="scope.row.fullRule === 2">每满</span>
          <!-- <span v-if="scope.row.fullRule === 3">金额</span>
          <span v-if="scope.row.fullRule === 4">数量</span> -->
        </template>
      </el-table-column>
      <!-- <el-table-column prop="fullReturnMoney" label="数值" align="center" width="60"></el-table-column> -->
      <el-table-column prop="startTime" label="活动开始时间" align="center" width="180"></el-table-column>
      <el-table-column prop="endTime" label="活动结束时间" align="center" width="180"></el-table-column>
      <el-table-column prop="createBy" label="申请人" align="center" width="100"></el-table-column>
      <el-table-column prop="createTime" label="申请时间" align="center" width="180"></el-table-column>
      <el-table-column prop="agreeTime" label="审核通过时间" align="center" width="180"></el-table-column>
      <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip  width="100"></el-table-column>
      <el-table-column prop="state" label="批次状态" align="center" width="120"></el-table-column>
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template scope="scope">
          <el-button v-if="scope.row.state === '草稿' || scope.row.state === '审核不通过'" @click="handle(scope.$index, scope.row, $event)" size="small">编辑</el-button>
          <el-button v-if="scope.row.state === '待审核' || scope.row.state === '审核中' || scope.row.state === '审核不通过' || scope.row.state === '未开始' || scope.row.state === '进行中'
          || scope.row.state === '已结束' || scope.row.state === '已作废'" @click="handle(scope.$index, scope.row, $event)" size="small">详情</el-button>
          <el-button v-if="scope.row.state === '草稿' || scope.row.state === '审核不通过'" @click="handle(scope.$index, scope.row, $event)" size="small">删除</el-button>
          <el-button v-if="scope.row.state === '待审核'" @click="handle(scope.$index, scope.row, $event)" size="small">撤回</el-button>
          <el-button v-if="scope.row.state === '未开始' || scope.row.state === '进行中'" @click="handle(scope.$index, scope.row, $event)" size="small">作废</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @current-change="handleCurrentChange"
      :page-size="Number(pageSize)"
      layout="total, prev, pager, next"
      :total="Number(total)"
      style="padding-top:10px;text-align: right;">
    </el-pagination>
    <el-dialog title="满返详情" :visible.sync="fullDetail">
      <div class="detail-info" style="margin-top: 43px">
        <div class="form-item">
          <h4>基本信息</h4>
          <el-form label-width="180px">
            <el-row>
                <el-form-item label="所属分公司">
                  <span>{{this.detailData.branchName}}</span>
                </el-form-item>
                <el-form-item label="所属部门">
                  <span>{{this.detailData.departName}}</span>
                </el-form-item>
                <el-form-item label="客资类型">
                  <span>{{this.detailData.customerName}}</span>
                </el-form-item>
                <el-form-item label="促销费用">
                  <span>{{this.detailData.cxName}}</span>
                </el-form-item>
                <el-form-item v-if="this.detailData.providerRatio !== 0" label="供应商占比">
                  <span>{{this.detailData.providerRatio}}</span>
                </el-form-item>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 43px">
        <div class="form-item">
          <h4>批次信息</h4>
          <el-form label-width="180px">
            <el-row>
                <el-form-item label="批次名称">
                  <span>{{this.detailData.batchName}}</span>
                </el-form-item>
                <el-form-item label="活动起止时间">
                  <span>{{this.timeDeltSecond(this.detailData.startTime)}}</span> -
                  <span>{{this.timeDeltSecond(this.detailData.endTime)}}</span>
                </el-form-item>
                <el-form-item label="展示时间">
                  <span>{{this.timeDeltSecond(this.detailData.showStartTime)}}</span> -
                  <span>{{this.timeDeltSecond(this.detailData.showEndTime)}}</span>
                </el-form-item>
                <el-form-item label="满返纬度">
                  <span v-if="this.detailData.latType === 1">订单</span>
                  <span v-if="this.detailData.latType === 2">部分商品</span>
                </el-form-item>
                <el-form-item label="满返规则">
                  <span v-if="this.detailData.fullRule === 1">阶梯</span>
                  <span v-if="this.detailData.fullRule === 2">每满</span>
                </el-form-item>
                <el-form-item label="">
                  <span v-if="this.detailData.fullRuleRule === 1">金额</span>
                  <span v-if="this.detailData.fullRuleRule === 2">数量</span>
                </el-form-item>
                <el-form-item v-if="this.detailData.fullRuleRule === 1" label="满返金额">
                  <span>{{this.detailData.fullReturnMoney}}</span>
                </el-form-item>
                <el-form-item v-if="this.detailData.fullRuleRule === 2" label="满返数量">
                  <span>{{this.detailData.fullReturnMoney}}</span>
                </el-form-item>
                <el-form-item v-if="this.detailData.fullRule === 2" label="参与次数">
                  <span v-if="this.detailData.joinType === 1">不限</span>
                  <span v-if="this.detailData.joinType === 2">全程</span>
                  <span v-if="this.detailData.joinType === 3">每单</span>
                </el-form-item>
                <el-form-item v-if="this.detailData.joinType === 3 || this.detailData.joinType === 2" label="反">
                  <span>{{this.detailData.returnTimes}} 次</span>
                </el-form-item>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 43px">
        <div class="form-item">
          <h4>优惠券信息</h4>
          <el-table v-if="fullDetail" :data="this.detailData.tickets" border>
            <el-table-column v-if="this.detailData.latType === 1 && this.detailData.fullRule ===1" prop="fullMoney" label="满足金额" align="center" width="90"></el-table-column>
            <el-table-column prop="ticketId" label="优惠券ID" align="center" width="90"></el-table-column>
            <el-table-column prop="ticketName" label="优惠券名称" align="center" width="100"></el-table-column>
            <el-table-column prop="ticketType" label="优惠券类型" align="center" width="100"></el-table-column>
            <el-table-column prop="ticketMoney" label="面值" align="center" width="50"></el-table-column>
            <el-table-column prop="fullUse" label="满多少可用" align="center" width="100"></el-table-column>
            <el-table-column prop="expiryDateType" label="有效期类型" align="center" width="100">
              <template scope="scope" >
                <span v-if="scope.row.expiryDateType==='1'">时间段</span>
                <span v-if="scope.row.expiryDateType==='2'">截止时间</span>
                <span v-if="scope.row.expiryDateType==='3'">天数</span>
              </template>
            </el-table-column>
            <el-table-column label="有效期" align="center">
              <template scope="scope">
                <span v-if="scope.row.expiryDateType==='1'">{{scope.row.startTime}}-{{scope.row.endTime}}</span>
                <span v-if="scope.row.expiryDateType==='2'">{{scope.row.endTime}}</span>
                <span v-if="scope.row.expiryDateType==='3'">{{scope.row.days}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="ticketUser" label="建券人" align="center" width="70"></el-table-column>
            <!-- <el-table-column prop="historyTotal" label="累计已发放张数" align="center" width="100"></el-table-column>
            <el-table-column prop="todayTotal" label="今日已发放张数" align="center" width="100"></el-table-column> -->
          </el-table>
        </div>
      </div>
      <div v-if="productsDetail" class="detail-info" style="margin-top: 43px">
        <div class="form-item">
          <h4>商品信息</h4>
          <el-table v-if="productsDetail" :data="this.detailData.products" border>
            <el-table-column prop="productId" label="商品ID" align="center"></el-table-column>
            <el-table-column prop="productName" label="商品名称" align="center"></el-table-column>
            <el-table-column prop="units" label="单位" align="center"></el-table-column>
            <el-table-column prop="productSize" label="规格" align="center"></el-table-column>
            <el-table-column prop="price" label="销售价" align="center"></el-table-column>
            <el-table-column prop="lastPrice" label="最近一次采购价" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
      <div class="detail-info" style="margin-top: 43px;margin-bottom:80px">
        <div class="form-item">
          <h4>审核信息</h4>
          <el-table :data="couponInfoList" border>
            <el-table-column label="审核人名称" align="center"></el-table-column>
            <el-table-column label="任务内容" align="center"></el-table-column>
            <el-table-column label="审核结果" align="center"></el-table-column>
            <el-table-column label="审核意见" align="center"></el-table-column>
            <el-table-column label="审核时间" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="导出字段筛选" size="small" :visible.sync="checkColumn">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedOptions" @change="handleCheckedCitiesChange">
        <el-checkbox
          v-for="item in Options"
          :label="item.name">
          {{item.text}}
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportFile">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { getInfo, activity } from '../../../../config/proxy.js'
  // import { mapState } from 'vuex'
  import mixins from '../../../../components/mixins.vue'
  import { apiHost, apiURL } from '../../../../config/settings.js'
  export default {
    mixins: [mixins],
    data () {
      return {
        pickerOptions1: {
          disabledDate (time) {
            console.log(time.getTime())
            return time.getTime() < new Date('2017-10-10').getTime() || time.getTime() > new Date('2017-11-10').getTime()
          }
        },
        checkAll: false,
        isIndeterminate: true,
        checkedOptions: [],   // 选中的
        Options: [],          // 选项集合
        checkColumn: false,   // 导出字段筛选弹窗
        checkedShow: [],      // 全选展示
        formInline: {
          branchId: '',
          deptId: '',
          state: '',
          sendTime: '',
          stime: '',
          etime: '',
          batchId: '',
          batchName: '',
          startStopTime: ''
        },
        pageSize: 10,
        total: '',
        page: 1,
        basicInfo: {
          branch: '',
          department: '',
          cost: '',
          suppliers: '',
          promotions: '',
          email: '',
          etime: ''
        },
        fullDetail: false,
        branchList: [],
        couponInfoList: [],
        checkInfoList: [],
        departmentList: [],
        tableData: [],
        isLoading: false,
        // pageData: {
        //   pageSize: 10,
        //   page: 1
        // },
        // total: '',
        //      详情弹窗
        detailData: {},
        detailDialog: false,
        productsDetail: false,
        showBranch: '',
        showDept: '',
        brachDisabled: false,
        deptList: [],
        visible: false
      }
    },
    methods: {
      handleCheckAllChange (val) {
        this.checkedOptions = val ? this.checkedShow : []
        this.isIndeterminate = false
      }, // 全选
      handleCheckedCitiesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.Options.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.Options.length
      }, // 单选
      exportFile () {
        if (this.checkedOptions.length === 0) {
          this.message('请勾选要导出的项', 'error')
          return false
        }
        this.formInline.couponType = 13
        this.formInline.page = this.page
        this.formInline.pageSize = this.pageSize
        this.formInline.reqColumnName = this.checkedOptions
        var _data = this.formInline
        var form = document.createElement('form')
        document.body.appendChild(form)
        form.method = 'post'
        form.action = 'http://' + apiHost.newCms + ':20000' + apiURL.yhqhd_export
        // console.log(params.length)
        for (var i in _data) {
          var newInput = document.createElement('input')
          newInput.setAttribute('name', i)
          newInput.setAttribute('type', 'hidden')
          newInput.setAttribute('value', _data[i])
          form.appendChild(newInput)
        }
        form.submit()
        form.remove()
      }, // 导出
      pageChange () {
        this.page = 1
      },
      getDeptList (val) { // 获取部门
        console.log(this.visible)
        if (this.visible === true) {
          console.log('aaa')
          this.formInline.deptId = ''
        }
        var _data = {}
        this.branchList.forEach(element => {
          if (val === element.branch_Id) {
            _data.orgId = element.org_id
          }
        })
        console.log(_data)
        getInfo.department(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            if (val === 1) {
              this.deptList = []
              res.content.forEach(element => {
                if (element.org_name.indexOf('公司') === -1) {
                  this.deptList.push(element)
                }
              })
              this.matchDept()
            } else {
              this.deptList = res.content
              this.matchDept()
            }
          } else {
            this.message(res.message, 'error')
          }
        })
      },
      matchDept () { // 匹配 当前登录人的部门与部门列表
        for (let index = 0; index < this.deptList.length; index++) {
          const element = this.deptList[index]
          if (Number(this.formInline.deptId) === Number(element.org_id)) {
            return
          } else {
            if (index === this.deptList.length - 1) {
              this.formInline.deptId = ''
            }
          }
        }
      },
      visibleChange (a) {
        console.log(a)
        this.visible = a
      },
      templateAdd () { // 新增定投
        this.openNewWindow('mfgl_add', '新增满返', 'mfgl_add')
      },
      searchList () { // 查询
        // this.tableData = []
        this.isLoading = true
        // var _data = Object.assign(this.formInline, this.pageData)
        var _data = {
          branchId: this.formInline.branchId, // 分公司id、
          departmentId: this.formInline.deptId, // 部门id
          startTime: this.formInline.stime, // 开始时间
          endTime: this.formInline.etime, // 结束时间
          batchId: this.formInline.batchId, // 批次 id
          phpId: this.formInline.phpId, // 批次 id
          page: this.page,
          pageSize: this.pageSize,
          batchName: this.formInline.batchName, // 批次名称
          state: this.formInline.state === '' ? '' : Number(this.formInline.state)
        }
        console.log(_data)
        activity.yhqhd.mfgl.list(_data, (res) => { // 查询
          // console.log(_data)
          console.log(res)
          if (res.message === 'ok') {
            this.isLoading = false
            this.tableData = res.content.content
            this.total = res.content.count
            this.page = res.content.page
            this.matchState(this.tableData)
            // console.log(this.tableData)
          } else {
            this.message('查询失败', 'error')
          }
        })
      },
      matchState (res) { // 匹配状态
        if (res) {
          for (var i = 0; i < res.length; i++) {
            if (res[i].state === 1) { res[i].state = '草稿' }
            if (res[i].state === 2) { res[i].state = '待审核' }
            if (res[i].state === 3) { res[i].state = '审核中' }
            if (res[i].state === 4) { res[i].state = '审核不通过' }
            if (res[i].state === 5) { res[i].state = '未开始' }
            if (res[i].state === 6) { res[i].state = '进行中' }
            if (res[i].state === 7) { res[i].state = '已结束' }
            if (res[i].state === 99) { res[i].state = '已作废' }
          }
        }
      },
      handleCurrentChange (val) { // 分页
        this.page = val
        this.tableData = []
        this.isLoading = true
        this.searchList()
      },
      handle (index, row, event) { // 操作
        // console.log(event)
        const handleName = event.target.innerText
        console.log(handleName)
        switch (handleName) {
          case '详情':
            // this.openNewWindow('dtglDetail', '定投详情', 'dtglDetail', row.id)
            // this.fullDetail = true
            // activity.yhqhd.mfgl.detail({id: row.id}, (res) => {
            //   console.log(res)
            //   if (res.message === 'ok') {
            //     this.detailData = res.content
            //     this.detailDialog = true
            //     if (res.content.products !== null) {
            //       this.productsDetail = true
            //     } else {
            //       this.productsDetail = false
            //     }
            //   } else {
            //     this.message('查看详情', 'error')
            //   }
            // })
            this.openNewWindow('mfgl_detail', '满返详情', 'mfgl_detail', row.id)
            break
          case '编辑':
            this.openNewWindow('mfgl_bj', '编辑满返', 'mfgl_add', row)
            break
          case '删除':
            this.buttonPublicMethods('删除', 'delete', row)
            break
          case '撤回':
            this.buttonPublicMethods('撤回', 'invoke', row)
            break
          case '作废':
            this.buttonPublicMethods('作废', 'cancel', row)
            break
          case '发券':
            this.buttonPublicMethods('发券', 'sendTicket', row)
            break
          default:
            break
        }
      },
      buttonPublicMethods (text, fnNane, row) { // 删除 撤回 作废 发券公共方法
        this.$confirm('您确定要' + text + '吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var _data = {}
          if (text === '发券') {
            _data.id = row.id
            _data.doAction = row.doAction
          } else if (text === '撤回') {
            _data.id = row.id
            _data.userName = this.userName
            _data.userId = 13370
          } else {
            _data.id = row.id
          }
          console.log(_data)
          console.log(fnNane)
          activity.yhqhd.mfgl[fnNane](_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.searchList()
              this.message(text + '成功', 'success')
            } else {
              this.message(text + '失败', 'error')
            }
          })
        }).catch(() => {
        })
      },
      daterangeFormat (t) { // 时间段格式化
//        this.formInline.stime = t[0]
//        this.formInline.etime = t[1]
        if (t) {
          this.formInline.stime = t[0]
          this.formInline.etime = t[1]
        } else {
          this.formInline.stime = ''
          this.formInline.etime = ''
        }
      },
      timeDeltSecond (d) { // 时间去秒
        if (d) {
          return d.split(' ')[0]
        }
      },
      // openNewWindow (menuId, menuName, perController, uid) { // 新增tab方法
      //   var _data = {
      //     menu_id: menuId,
      //     menu_name: menuName,
      //     per_controller: perController
      //   }
      //   if (uid) {
      //     _data.uid = uid
      //   }
      //   this.$store.dispatch('addTab', _data)
      // },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    created () {
      if (this.branchId === 1) {
        this.brachDisabled = false
        this.formInline.branchId = this.branchId
        this.formInline.deptId = this.deptId
      } else {
        this.brachDisabled = true
        this.showBranch = this.branchName
        this.showDept = this.deptName
        this.formInline.branchId = this.branchId
        this.formInline.deptId = this.deptId
        console.log(this.branchId)
        // this.formInline.branchId = this.branchId
      }
      getInfo.getColumns({promotion_type: 13}, res => {
        this.Options = res.content
        this.Options.forEach(item => {
          this.checkedShow.push(item.name)
        })
      })
    },
    computed: {
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.mfState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      }
    },
    watch: {
      update_state (curVal, oldVal) {  // 监听 更新状态 查询list
        this.searchList()
      },
      branchList (a, b) {
        if (this.branchId === 1) {
          this.getDeptList(1)
        }
      }
    }
  }
</script>
<style>
.line{
	margin-left:20px;
	text-align:center
}
.el-button+.el-button{
  margin-left: 0
}
.el-table .cell, .el-table th>div{
  padding-left:10px;
  padding-right:10px;
}
.el-dialog--small{
  width:60%
}
</style>
